package com.cyclinggle.cloud.common.intercepter;

import java.io.IOException;
import java.util.Map;

import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;

import com.cyclinggle.cloud.common.context.UserContextHolder;
import com.cyclinggle.cloud.common.vo.User;

/**
 * @Project       : ch10-1-common
 * @Program Name  : com.cyclinggle.cloud.common.intercepter.RestTemplateUserContextInterceptor.java
 * @Description   : RestTemplate传递用户上下文
 * @Author        : wangchao
 * @Creation Date : 2019年3月29日 上午11:03:03 
 * @ModificationHistory  
 * Who          When             What 
 * ----------   -------------    -----------------------------------
 * wangchao     2019年3月29日        create
 */
public class RestTemplateUserContextInterceptor implements ClientHttpRequestInterceptor {

	@Override
	public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
			throws IOException {
		User user = UserContextHolder.currentUser();
		Map<String, String> headers = user.toHttpHeaders();
		for (Map.Entry<String, String> header : headers.entrySet()) {
			request.getHeaders().add(header.getKey(), header.getValue());
		}
		// 调用
		return execution.execute(request, body);
	}
}
